package com.school.hjt.schoolclasscard.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.school.hjt.schoolclasscard.R;
import com.school.hjt.schoolclasscard.db.ClassAlbum;
import com.school.hjt.schoolclasscard.utlis.APPUtlis;

import java.io.File;
import java.util.List;

/**
 * Created by xqx on 2018/1/8.
 *
 */
public class RongYuAdapter extends RecyclerView.Adapter<RongYuHolder> {
    private View view;
    private List<Integer> heights;
    private LayoutInflater mInflater;
    private List<ClassAlbum> list;


    public RongYuAdapter(Context context, List<ClassAlbum> list) {
        mInflater = LayoutInflater.from(context);
        this.list=list;

//        heights = new ArrayList<Integer>();
//        for (int i = 0; i < list.size(); i++) {
//            heights.add((int) (600 + Math.random() * 300));
//        }
    }

    @Override
    public RongYuHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //利用反射将item的布局加载出来
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rongyu_item, null);
        //new一个我们的ViewHolder，findViewById操作都在LinearHolder的构造方法中进行了
        return new RongYuHolder(view);
    }

    @Override
    public void onBindViewHolder(final RongYuHolder holder, int position) {
        ViewGroup.LayoutParams layoutParams = holder.sg_item.getLayoutParams();
        LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)holder.ll_bg.getLayoutParams();
        ClassAlbum classAlbum = list.get(position);
        File file=new File(Environment.getExternalStorageDirectory().getPath() + "/Face/"+ APPUtlis.getMd5Value(classAlbum.getPic())+".hjt");
        if (file.exists()){
            int[] imageWidthHeight = getImageWidthHeight(file.getAbsolutePath());
            float com = com(imageWidthHeight[0]);
            int he= (int)(imageWidthHeight[1]/com);
            lp.height=he+60;
            holder.ll_bg.setLayoutParams(lp);
            layoutParams.height=he;
            Bitmap diskBitmap = getDiskBitmap(file.getAbsolutePath());
            holder.sg_item.setImageBitmap(diskBitmap);
            holder.ll_bg.setBackgroundResource(R.mipmap.rongyu);
            holder.tv_RongYu.setText(classAlbum.getTitle());
        }
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Log.e("ATGS",holder.sg_item.getWidth()+"");
//            }
//        },10000);
    }
    private Bitmap getDiskBitmap(String pathString)
    {
        Bitmap bitmap = null;
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathString, opts);
        opts.inSampleSize = computeSampleSize(opts, -1, 600 * 600);
        opts.inJustDecodeBounds = false;
        try {
            bitmap = BitmapFactory.decodeFile(pathString, opts);
//            imageView.setImageBitmap(bmp);
        } catch (OutOfMemoryError err) {

        }
        return bitmap;
    }
    private  int computeInitialSampleSize(BitmapFactory.Options options,
                                          int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }
    public  int computeSampleSize(BitmapFactory.Options options,
                                  int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }
    private float com(float w){
        float in ;
        in=w/510f;
        return in;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
    public static int[] getImageWidthHeight(String path){
        BitmapFactory.Options options = new BitmapFactory.Options();

        /**
         * 最关键在此，把options.inJustDecodeBounds = true;
         * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
         */
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回的bitmap为null
        /**
         *options.outHeight为原始图片的高
         */
        return new int[]{options.outWidth,options.outHeight};
    }

}

class RongYuHolder extends RecyclerView.ViewHolder{
    ImageView sg_item;
    LinearLayout ll_bg;
    TextView tv_RongYu;
    public RongYuHolder(final View itemView) {
        super(itemView);
        sg_item =itemView.findViewById(R.id.sg_item);
        ll_bg=itemView.findViewById(R.id.ll_bg);
        tv_RongYu=itemView.findViewById(R.id.tv_RongYu);
    }
}
